// pages/postList/postList.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pxTorpx: 2, //px转化为rpx的系数
    leftLooks: 660, //rpx
    topLooks: 790, //rpx
    widthScreen: null,
    heightScreen: null,
    navbarTitle: [
      "全部帖子",
      "热度排名"
    ],
    is_show: true,
    navbarActiveIndex: 0,
    isAddLike: false,
    page_cnt: 10,
    circleCnt: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var nowColor = app.globalData.nowColor;
    that.setData({
      nowColor: nowColor
    });
    wx.getSystemInfo({
      success: function(res) {
        //rpx
        that.setData({
          heightScreen: res.windowHeight * (750 / res.windowWidth),
        });
      }
    });
    var discussId = options.discuss_id;
    wx.setStorageSync('discuss_id', discussId);
    var judge = options.judge;
    var that = this;
    var user_id = wx.getStorageSync('user_id');
    that.setData({
      discussId: discussId,
      judge: judge,
      my_user_id: user_id,
      nowSkinUrl: app.globalData.nowSkinUrl
    })
    that.onGetCircle(discussId); //加载圈子信息
    that.onGetTopics(); //加载圈子里的所有帖子信息
    var pxTorpx = that.data.pxTorpx;
    //获取屏幕高宽
    wx.getSystemInfo({
      success: function(res) {
        //rpx
        that.setData({
          widthScreen: res.windowWidth * (750 / res.windowWidth),
          heightScreen: res.windowHeight * (750 / res.windowWidth),
          pxTorpx: (750 / res.windowWidth)
        });
      }
    });
  },



  //将编码后的八进制的emoji表情重新解码成十六进制的表情字符

  entitiesToUtf16: function(str) {

    return str.replace(/&#(\d+);/g, function(match, dec) {

      let H = Math.floor((dec - 0x10000) / 0x400) + 0xD800;

      let L = Math.floor(dec - 0x10000) % 0x400 + 0xDC00;

      return String.fromCharCode(H, L);

    });

  },
  //关注按钮
  onBindAttention: function() {
    var that = this;
    var judge = that.data.judge;
    var user_id = wx.getStorageSync('user_id');
    var discuss_id = that.data.discussId;
    if (judge == 1) {
      that.setData({
        judge: 0
      })
      wx.request({
        url: app.globalData.targetUrl + 'discuss/collect/',
        //method: 'DELETE',
        data: {
          user_id: user_id,
          discuss_id: discuss_id,
          is_delete: 1
        },
        success: res => {
          that.onGetCircle(discuss_id); //刷新
        }
      })
    } else {
      that.setData({
        judge: 1
      })
      wx.request({
        url: app.globalData.targetUrl + 'discuss/collect/',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          user_id: user_id,
          discuss_id: discuss_id
        },
        success: res => {
          that.onGetCircle(discuss_id); //刷新
        }
      })
    }
  },

  onShow: function() {
    var that = this;
    var nowColor = app.globalData.nowColor;
    that.setData({
      nowColor: nowColor
    });
    var animation = wx.createAnimation({});
    var time = 440;
    var widthScreen = this.data.widthScreen;
    var heightScreen = this.data.heightScreen;
    var leftLooks = that.data.leftLooks;
    var topLooks = that.data.topLooks;
    var pxTorpx = that.data.pxTorpx;
    that.onGetCircle(that.data.discussId); //加载圈子信息
    that.onGetTopics(); //加载圈子里的所有帖子信息
    animation.translate(0, 0).scale(1).opacity(1).step({
      duration: time
    })
    that.setData({
      queueData: animation.export()
    })
    app.globalData.isReturn = false;
  },

  //得到圈子信息
  onGetCircle: function(discussId) {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/' + discussId + '/',
      method: 'GET',
      success: res => {
        var circle = res.data.data;
        that.setData({
          circle: circle
        })
      }
    })
  },

  //热度排名--所有帖子信息
  onGetHeatTopics: function() {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/',
      method: "GET",
      data: {
        now_page: 1,
        page_cnt: that.data.page_cnt,
        discuss_id: that.data.discussId,
        type_id: 1
      },
      success: res => {
        var list = res.data.data;
        var main = [];
        var k = 0;
        var image_urls = [];
        for (var i = 0; i < list.length; i++) {
          if (list[i].type_id == 1 && list[i].discuss_id == that.data.discussId) {
            main[k] = list[i];
            k++;
          }
        }
        var temp;
        for (var i = 0; i < main.length; i++) {
          var temp1 = parseInt(main[i].view_cnt) + parseInt(main[i].like_cnt) + parseInt(main[i].comment_cnt) + parseInt(main[i].collect_cnt); //由浏览量+点赞数+评论数+收藏数
          for (var j = i + 1; j < main.length; j++) {
            var temp2 = parseInt(main[j].view_cnt) + parseInt(main[j].like_cnt) + parseInt(main[j].comment_cnt) + parseInt(main[j].collect_cnt); //由浏览量+点赞数+评论数+收藏数
            if (temp1 < temp2) {
              temp = main[i];
              main[i] = main[j];
              main[j] = temp;
            }
          }
          if (main[i].image_urls != '') {
            image_urls[i] = main[i].image_urls[0].slice(0, main[i].image_urls.length - 5) + "_tb.jpg";
          } else {
            image_urls[i] = '';
          }
        }
        for (var i = 0; i < main.length; i++) {
          main[i].description = that.entitiesToUtf16(main[i].description)
        }
        if (main.length == 0) {
          that.onReachBottom();
        } else {
          that.setData({
            list: main,
            circleCnt: main.length,
            image_urls: image_urls
          })
        }
      }
    })
  },

  //得到圈子中所有帖子信息
  onGetTopics: function() {
    var that = this;
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/',
      method: "GET",
      data: {
        now_page: 1,
        page_cnt: that.data.page_cnt,
        discuss_id: that.data.discussId,
        type_id: 1
      },
      success: res => {
        var list = res.data.data;
        var main = [];
        var k = 0;
        var image_urls = [];
        for (var i = 0; i < list.length; i++) {
          if (list[i].type_id == 1 && list[i].discuss_id == that.data.discussId) {
            main[k] = list[i];
            if (list[i].image_urls != '') {
              image_urls[k] = list[i].image_urls[0].slice(0, list[i].image_urls.length - 5) + "_tb.jpg";
            } else {
              image_urls[k] = '';
            }
            k++;
          }
        }
        for (var i = 0; i < main.length; i++) {
          main[i].description = that.entitiesToUtf16(main[i].description)
        }
        if (main.length == 0 && that.data.is_show) {
          that.onReachBottom();
        } else {
          that.setData({
            list: main,
            circleCnt: main.length,
            image_urls: image_urls
          })
        }
      }
    })
  },

  //
  onHide: function() {
    var that = this;
    that.setData({
      is_show: false
    })
  },

  onUnload: function() {
    var that = this;
    that.setData({
      is_show: false
    })
  },

  //顶部导航条跳动
  onNavBarTap: function(event) {
    var that = this;
    // 获取点击的navbar的index
    let navbarTapIndex = event.currentTarget.dataset.navbarIndex
    // 设置data属性中的navbarActiveIndex为当前点击的navbar
    this.setData({
      navbarActiveIndex: navbarTapIndex
    })
    if (navbarTapIndex == 1) that.onGetHeatTopics();
    else that.onGetTopics();
  },



  //小松鼠动画
  ClickFairy: function() {
    var that = this;
    var animation = wx.createAnimation({});
    var time = 440;
    var widthScreen = this.data.widthScreen;
    var heightScreen = this.data.heightScreen;
    var leftLooks = that.data.leftLooks;
    var topLooks = that.data.topLooks;
    var pxTorpx = that.data.pxTorpx;
    //console.log(widthScreen, heightScreen, leftLooks, topLooks);
    //console.log((widthScreen / 2 - leftLooks));
    animation.translate(((widthScreen / 2 - leftLooks) - 20) / pxTorpx, ((heightScreen / 2 - topLooks) - 20) / pxTorpx).scale(0).opacity(0.4).step({
      duration: time
    })
    this.setData({
      queueData: animation.export()
    })
    this.sleep(time);
    wx.navigateTo({
      url: '/pages/launchTopic/launchTopic?discussId=' + that.data.discussId + '&title=' + that.data.circle.thumb_url
    })

  },
  imagetouchmove: function(e) {
    var that = this;
    var pxTorpx = that.data.pxTorpx;
    var left = e.touches[0].clientX * pxTorpx - 45; //rpx
    var top = e.touches[0].clientY * pxTorpx - 45; //rpx
    if (left < 0 && left) {
      left = 0
    };
    if (left > that.data.widthScreen - 90) {
      left = that.data.widthScreen - 90
    };
    if (top < 0) {
      top = 0
    };
    if (top > that.data.heightScreen - 190) {
      top = that.data.heightScreen - 190
    };

    that.setData({
      leftLooks: left,
      topLooks: top
    })
  },
  imagetouchend: function(e) {
    var that = this;
    var animation = wx.createAnimation({});
    var widthScreen = this.data.widthScreen;
    var left_before = that.data.leftLooks;
    if (left_before == that.data.widthScreen - 90) return;
    var left = that.data.widthScreen - 90;
    that.setData({
      leftLooks: left
    })
    var time = 300;
    console.log(left_before);
    var n1 = left_before / widthScreen; //形变系数
    if (n1 < 0.2) {
      n1 = 0.2
    }
    var n2 = (widthScreen - left_before) / widthScreen * 0.7;
    var pxTorpx = that.data.pxTorpx;
    console.log(pxTorpx);
    console.log("n1:", 1 - n1, (90 / pxTorpx) * (1 - n1));
    animation.scale(n1, 1 + n2).translate((90 / pxTorpx) * (1 - n1), 0).step({
      duration: time
    });
    that.setData({
      queueData: animation.export()
    });
    that.sleep(time);
    animation.scale(1, 1).translate(0, 0).step({
      duration: time
    });
    that.setData({
      queueData: animation.export()
    });

  },

  //延时函数
  sleep: function(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
        return;
    }
  },
  onReachBottom: function() {
    var that = this;
    var page_cnt = that.data.page_cnt + 10;
    this.setData({
      page_cnt: page_cnt
    })
    that.onGetTopics();
  },
})